// pages/friends/createAccount/index.ts
import tran from '../../../utils/language';
import { commonTagList, userInfoStepOne } from '../../../utils/api.js'
import dayjs from 'dayjs'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: tran._t('createAccount'),
    _tBase: tran._t('base'),
    navBarHeight: getApp().globalData.navBarHeight,
    columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
    pickerParams: {
      show: false,
      pickerType: 'MBTI',
      // defaultValue: dayjs().format('YYYY-MM-DD')
      defaultValue: ''
    },
    confirmPopup: {
      showPopup: false,
      topTitle: tran._t('base').topTitleTip,
      midText: tran._t('base').exitEditTip,
      confirmText: tran._t('base').confirmText,
      closeText: tran._t('base').closeBtnText,
    },
    pickerRegionParams: {
      show: false,
      pickerType: 'region'
    },
    pickerGenderParams: {
      show: false,
      pickerType: 'MBTI',
      defaultValue: '',
      title: '性格类型'
    },
    formData: {
      fullName: '', // 姓名
      nickname: '', // 昵称
      onlyShowNickname: false, // 是否显示昵称
      birthDate: '', // 生日
      userGender: '', // 性别（0：未知，1：男，2：女
      genderText: '',
      languageText: '',
      languages: '', // 语言
      professionId: '', // 职业技能ID
      professionName: '',
      currentProvinceCode: '', // 居住的省code
      currentProvinceName: '', // 省
      currentCityCode: '', // 居住地址-市-code
      currentCityName: '', // 居住地址-市
      currentDistrictCode: '', // 居住地址-区-code
      currentDistrictName: '', // 居住地址-区
      hometownProvinceCode: '', // 家乡地址-省-code
      hometownProvinceName: '', // 家乡地址-省
      hometownCityCode: '', // 家乡地址-市-code
      hometownCityName: '', // 家乡地址-市
      hometownDistrictCode: '', // 家乡地址-区-code
      hometownDistrictName: '', // 家乡地址-区
    },
    commonPickerType: '',
    commonPickerParams: {
      show: false,
      pickerType: 'MBTI',
      defaultValue: '',
      data: [] as commonPickerDataType[]
    },
    pickerLangParams: {
      show: false,
      pickerType: 'language',
      defaultValue: '',
      data: [] as commonPickerDataType[]
    },
    commonPickerData: [] as commonPickerDataType[],
    langList: [],
    professionList: [],
    pickerSkillParams: {
      show: false,
      pickerType: 'skill',
      defaultValue: '',
      data: [] as commonPickerDataType[]
    },
    pickerAreaParams: {
      show: false,
      pickerType: 'areaRegion',
      defaultValue: [''],
      data: [] as commonPickerDataType[]
    },
    pickerHomeAreaParams: {
      show: false,
      pickerType: 'areaHomeRegion',
      defaultValue: [''],
      data: [] as commonPickerDataType[]
    },
    loginInfo: {
      birthDate: ''
    },
    currentRegion: [''],
    homeRegion: [''],
    genderList: [
      {
        text: '女性',
        value: '2',
        selectFlag: false
      },
      {
        text: '男性',
        value: '1',
        selectFlag: false
      },
      {
        text: '其他',
        value: '0',
        selectFlag: false
      }],
    nextTapFlag: false,
    registerFlag: '',
    isEdit: getApp().globalData.profileFrom === 'edit'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    if (options && Object.keys('options').length > 0) {
      this.setData({
        registerFlag: options.type
      })
    }
    this.getLangList()
    const loginInfo = wx.getStorageSync('userInfo')
    let { formData, genderList } = this.data
    const professionList = wx.getStorageSync('professionList')
    if (professionList && professionList.length > 0) {
      this.setData({
        professionList
      }, () => {
        this.handleSkill()
      })
    } else {
      this.getProfession()
    }
    if (loginInfo && Object.keys(loginInfo).length > 0) {
      // if (getApp().globalData.profileFrom == 'edit') { // 是编辑, 回显数据处理
      // 性别
      const genderArr = genderList.filter(item => item.value == loginInfo.userGender)
      formData.genderText = genderArr.length > 0 ? genderArr[0].text : ''
      // 语言
      const langList: any = this.data.langList || getApp().globalData.langList1
      let langTextCurrent: any = []
      let langValueCurrent: any = []
      console.log(langList,'次数');
      
      langList.length > 0 && langList.map((item: any) => {
        loginInfo.languages.length > 0 && loginInfo.languages.map((item1: any) => {
          if (item.value == item1) {
            langTextCurrent.push(item.text)
            langValueCurrent.push(item.value)
          }
        })
      })
      formData.languageText = langTextCurrent.length > 0 ? langTextCurrent.join(',') : ''
      formData.languages = langValueCurrent.length > 0 ? langValueCurrent.join(',') : ''
      // 职业
      const skillList: any = professionList
      const skillArr = skillList && skillList.length > 0 ? skillList.filter((item: any) => item.value == loginInfo.professionId) : []
      formData.professionName = skillArr.length > 0 ? skillArr[0].text : ''
      // 地区回显
      let currentTextRegion = [loginInfo.currentProvinceName, loginInfo.currentCityName, loginInfo.currentDistrictName]
      let homeTextRegion = [loginInfo.hometownProvinceName, loginInfo.hometownCityName, loginInfo.hometownDistrictName]
      this.setData({
        currentRegion: currentTextRegion,
        homeRegion: homeTextRegion
      })
      formData = { ...formData, ...loginInfo }
      // }
    }
    this.setData({
      loginInfo,
      formData,
    }, () => {
      this.checkNextTapFlag()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  handleSkill() {
    const { professionList, formData } = this.data
    const loginInfo = wx.getStorageSync('userInfo')
    const skillList: any = professionList
    const skillArr = skillList.filter((item: any) => item.value == loginInfo.professionId)
    formData.professionName = skillArr.length > 0 ? skillArr[0].text : ''
    this.setData({
      formData
    })
  },
  onBack() {
    const { registerFlag, confirmPopup } = this.data
    if (registerFlag == 'register') { // 注册
      confirmPopup.showPopup = true
      this.setData({
        confirmPopup
      })
    } else { // 编辑
      wx.navigateBack()
    }
  },
  confirmFn() {
    wx.switchTab({
      url: '/pages/home/index'
    })
    this.closeFn()
  },
  closeFn() {
    const { confirmPopup } = this.data
    confirmPopup.showPopup = false
    this.setData({
      confirmPopup
    })
  },
  checkNextTapFlag() {
    const { nickname, birthDate, genderText, languageText } = this.data.formData
    if (nickname && birthDate && genderText && languageText) {
      this.setData({
        nextTapFlag: true
      })
    } else {
      this.setData({
        nextTapFlag: false
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  handleCommonSkillPicker(e: baseEvent) {
    const { pickerSkillParams, formData } = this.data
    const type = e.currentTarget.dataset.type;
    pickerSkillParams.pickerType = type
    pickerSkillParams.show = true
    pickerSkillParams.defaultValue = formData.professionId
    this.setData({ pickerSkillParams, commonPickerType: type })
  },
  handleCommonAreaPicker(e: baseEvent) {
    const { pickerAreaParams, formData, currentRegion } = this.data
    const type = e.currentTarget.dataset.type;
    pickerAreaParams.pickerType = type
    pickerAreaParams.show = true
    // pickerAreaParams.defaultValue = [formData.currentProvinceName, formData.currentCityName, formData.currentDistrictName]
    pickerAreaParams.defaultValue = currentRegion
    this.setData({ pickerAreaParams, commonPickerType: type })
  },
  handleCommonHomeAreaPicker(e: baseEvent) {
    console.log(e);
    
    const { pickerHomeAreaParams, formData, homeRegion } = this.data
    const type = e.currentTarget.dataset.type;
    pickerHomeAreaParams.pickerType = type
    pickerHomeAreaParams.show = true
    pickerHomeAreaParams.defaultValue = homeRegion
    this.setData({ pickerHomeAreaParams, commonPickerType: type })
  },
  /**
   * 从app.ts里面获取全局的语言列表
   */
  getLangList() {
    let list = getApp().globalData.langList1
    let langList: any = []
    list.length > 0 && list.map((item: any) => {
      const obj = {
        selectFlag: false,
        ...item
      }
      langList.push(obj)
    })
    this.setData({
      langList
    })
  },
  /**
    * 获取职业技能列表
    */
  getProfession() {
    let params = {
      tagType: 'SKILL'
    }
    commonTagList(params).then(res => {
      res.length > 0 && res.map((item: any) => {
        item.text = item.tagName
        item.selectFlag = false
        item.value = item.tagTypeId
      })
      this.setData({
        professionList: res
      }, () => {
        this.handleSkill()
      })
    })
  },
  handleLanguagePicker(e: baseEvent) {
    const { pickerLangParams, formData } = this.data
    const type = e.currentTarget.dataset.type;
    pickerLangParams.pickerType = type
    pickerLangParams.show = true
    pickerLangParams.defaultValue = formData.languages || ''
    this.setData({ pickerLangParams, commonPickerType: type }, () => {
      this.checkNextTapFlag()
    })
  },
  handleGenderPicker(e: baseEvent) {
    const { pickerGenderParams, formData, genderList } = this.data
    const type = e.currentTarget.dataset.type;
    pickerGenderParams.pickerType = type
    pickerGenderParams.show = true
    pickerGenderParams.defaultValue = formData.userGender
    this.setData({ pickerGenderParams, genderList: genderList, commonPickerType: type }, () => {
      this.checkNextTapFlag()
    })
  },
  fullNameChange(e: any) {
    console.log(e);
    
    const { formData } = this.data
    formData.fullName = e.detail.value
    this.setData({
      formData
    })
  },
  nickNameChange(e: any) {
    const { formData } = this.data
    formData.nickname = e.detail.value
    this.setData({
      formData
    }, () => {
      this.checkNextTapFlag()
    })
  },
  /**
   * 区域选择器确认按钮
   * @param e 
   */
  commonAreaPickerConfirm(e: any) {
    const obj = e.detail.value
    if (obj && Object.keys(obj).length > 0) {
      const { formData } = this.data
      formData.currentProvinceName = obj.provincesLabel
      formData.currentProvinceCode = obj.provincesValue
      formData.currentCityName = obj.cityLabel
      formData.currentCityCode = obj.cityValue
      formData.currentDistrictName = obj.regionLabel
      formData.currentDistrictCode = obj.regionValue
      this.setData({ formData })
    }
  },
  /**
   * 区域选择器确认按钮
   * @param e 
   */
  commonHomeAreaPickerConfirm(e: any) {
    const obj = e.detail.value
    if (obj && Object.keys(obj).length > 0) {
      const { formData } = this.data
      formData.hometownProvinceName = obj.provincesLabel
      formData.hometownProvinceCode = obj.provincesValue
      formData.hometownCityName = obj.cityLabel
      formData.hometownCityCode = obj.cityValue
      formData.hometownDistrictName = obj.regionLabel
      formData.hometownDistrictCode = obj.regionValue
      this.setData({ formData })
    }
  },
  /**
   * 普通的选择器确认按钮
   * @param e 
   */
  commonPickerConfirm(e: any) {
    const { commonPickerType } = this.data
    const obj = e.detail.value
    const { formData } = this.data
    if (commonPickerType == 'language') { // 语言
      formData.languageText = obj.text
      formData.languages = obj.value
    } else if (commonPickerType == 'gender') { // 性别
      formData.genderText = obj.text
      formData.userGender = obj.value
    } else if (commonPickerType == 'skill') { // 技能
      formData.professionName = obj.text
      formData.professionId = obj.value
    }
    this.setData({
      formData
    }, () => {
      this.checkNextTapFlag()
    })
  },
  nextTap() {
    const { registerFlag } = this.data
    const { fullName, nickname, onlyShowNickname, birthDate, userGender, languages, professionId, currentProvinceCode, currentProvinceName, currentCityCode, currentCityName, currentDistrictCode, currentDistrictName, hometownProvinceCode, hometownProvinceName, hometownCityCode, hometownCityName, hometownDistrictCode, hometownDistrictName } = this.data.formData
    if (!nickname) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
      return false
    }
    if (!birthDate) {
      wx.showToast({
        title: '出生日期不能为空',
        icon: 'none'
      })
      return false
    }
    if (userGender) {

    }
    if (!userGender) {
      if (userGender == '0') {
        console.log('其他类型，所以不做处理');
      } else {
        wx.showToast({
          title: '性别不能为空',
          icon: 'none'
        })
        return false
      }
    }
    if (!languages) {
      wx.showToast({
        title: '语言不能为空',
        icon: 'none'
      })
      return false
    }
    let langParams = []
    if (Array.isArray(languages)) {
      langParams = languages
    } else {
      langParams.push(languages)
    }
    const params = {
      fullName, // 姓名
      nickname, // 昵称
      onlyShowNickname, // 是否显示昵称
      birthDate, // 生日
      userGender, // 性别（0：未知，1：男，2：女
      languages: languages ? langParams : [], // 语言
      professionId, // 职业技能ID
      currentProvinceCode, // 居住的省code
      currentProvinceName, // 省
      currentCityCode, // 居住地址-市-code
      currentCityName, // 居住地址-市
      currentDistrictCode, // 居住地址-区-code
      currentDistrictName, // 居住地址-区
      hometownProvinceCode, // 家乡地址-省-code
      hometownProvinceName, // 家乡地址-省
      hometownCityCode, // 家乡地址-市-code
      hometownCityName, // 家乡地址-市
      hometownDistrictCode, // 家乡地址-区-code
      hometownDistrictName, // 家乡地址-区
    }
    this.setData({
      nextTapFlag: false
    })
    userInfoStepOne(params).then(res => {
      // 因为请求里面都判断了状态码，所以走到这里，就是成功了
      // wx.showToast({
      //   title: '操作成功'
      // })
      let loginInfo = wx.getStorageSync('loginInfo')
      if (loginInfo.completedStep <= 1) {
        loginInfo.completedStep = 1
        wx.setStorageSync('loginInfo', loginInfo)
      }
      getApp().getUserInfo()
      wx.navigateTo({
        url: `/pages/profile/personalization/index?type=${registerFlag}`
      })
      setTimeout(() => {
        this.setData({
          nextTapFlag: true
        })
      }, 1000)
    })
  },
  pickerConfirm(e: any) {
    const { formData, pickerParams } = this.data
    const obj = e.detail
    if (Object.keys(obj).length > 0) {
      formData.birthDate = `${obj.year}-${obj.month}-${obj.day}`
      this.setData({
        formData
      }, () => {
        this.checkNextTapFlag()
      })
    }
    pickerParams.show = false
    this.setData({
      pickerParams
    })
  },
  handlePicker(e: baseEvent) {
    // 打开picker 设置对应的picker弹出类型
    const type = e.currentTarget.dataset.type;
    const { pickerParams, loginInfo } = this.data
    pickerParams.show = true
    pickerParams.pickerType = type
    pickerParams.defaultValue = loginInfo.birthDate || ''
    this.setData({ pickerParams }, () => {
      this.checkNextTapFlag()
    })
  },
  handleRegionPicker(e: any) {
    const { pickerRegionParams } = this.data
    pickerRegionParams.show = true
    this.setData({
      pickerRegionParams: pickerRegionParams
    })

  },
  pickerRegionCancle() {
    const { pickerRegionParams } = this.data
    pickerRegionParams.show = false
    this.setData({
      pickerRegionParams
    })
  },
  pickerHomeRegionCancle() {
    const { pickerHomeAreaParams } = this.data
    pickerHomeAreaParams.show = false
    this.setData({
      pickerHomeAreaParams
    })
  },
  pickerCancel(e: any) {
    this.setData({ pickerParams: { show: false, pickerType: '', defaultValue: '' } })
  },
  changeNikeNameVisible() {
    const { formData } = this.data
    formData.onlyShowNickname = !this.data.formData.onlyShowNickname
    this.setData({ formData })
  },
  bindCurrentRegionChange(e: any) {
    const { formData } = this.data
    const regionCodeList = e.detail.code
    const regionTextList = e.detail.value
    if (regionCodeList.length > 0) {
      formData.currentProvinceCode = regionCodeList[0]
      formData.currentCityCode = regionCodeList[1]
      formData.currentDistrictCode = regionCodeList[2]
    }
    if (regionTextList.length > 0) {
      formData.currentProvinceName = regionTextList[0]
      formData.currentCityName = regionTextList[1]
      formData.currentDistrictName = regionTextList[2]
    }
    this.setData({ formData })
  },
  bindHometownRegionChange(e: any) {
    const { formData } = this.data
    const regionCodeList = e.detail.code
    const regionTextList = e.detail.value
    if (regionCodeList.length > 0) {
      formData.hometownProvinceCode = regionCodeList[0]
      formData.hometownCityCode = regionCodeList[1]
      formData.hometownDistrictCode = regionCodeList[2]
    }
    if (regionTextList.length > 0) {
      formData.hometownProvinceName = regionTextList[0]
      formData.hometownCityName = regionTextList[1]
      formData.hometownDistrictName = regionTextList[2]
    }
    this.setData({ formData })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})